import './index.less';
import React, {useEffect, useRef, useState} from 'react';
export function LeftRuler(props: {top: number}) {
    const rulerRef = useRef<HTMLCanvasElement>(null);
    const [h, setH] = useState(1000);
    const uh = 10;
    const drawLine = (start: number[], end: number[]) => {
        const {current} = rulerRef;
        const ctx = current?.getContext('2d');
        if (ctx) {
            const fixWidth = 0.5;
            const [sx, sy] = start;
            const [ex, ey] = end;
            ctx.beginPath();
            ctx.moveTo(sy, sx + fixWidth);
            ctx.lineTo(ey, ex + fixWidth);
            ctx.lineWidth = 1;
            ctx.strokeStyle = '#a1a1a1';
            ctx.closePath();
            ctx.stroke();
        }
    };
    const drawText = (text: number, x: number) => {
        const {current} = rulerRef;
        const ctx = current?.getContext('2d');
        if (ctx) {
            const fixWidth = 0.5;
            ctx.font = '10px';
            ctx.fillStyle = '#fff';
            ctx.fillText(text + '', 2, x + 9.5);
        }
    };
    const draw = () => {
        const {current} = rulerRef;
        const ctx = current?.getContext('2d');
        const h = current?.offsetHeight;

        if (!h) return;
        ctx?.clearRect(0, 0, 20, h);
        for (let i = 0; i < h - props.top; i += uh) {
            if (i % (10 * uh) === 0) {
                drawText(i, i + props.top);
                drawLine([i + props.top, 20], [i + props.top, 0]);
            } else if (i % (5 * uh) === 0) {
                drawLine([i + props.top, 20], [i + props.top, 8]);
            } else {
                drawLine([i + props.top, 20], [i + props.top, 14]);
            }
        }
        if (props.top > 0) {
            for (let i = 0; i > 0 - props.top; i -= 10) {
                if (i % (10 * uh) === 0) {
                    drawText(i, i + props.top);
                    drawLine([i + props.top, 20], [i + props.top, 0]);
                } else if (i % (5 * uh) === 0) {
                    drawLine([i + props.top, 20], [i + props.top, 8]);
                } else {
                    drawLine([i + props.top, 20], [i + props.top, 14]);
                }
            }
        }
    };
    useEffect(() => {
        const {current} = rulerRef;
        if (current) {
            setH(current.offsetHeight);
        }

        draw();
    }, []);
    useEffect(() => {
        draw();
    }, [props.top]);
    return (
        <>
            <div className="left-ruler">
                <canvas ref={rulerRef} width={20} height={h}></canvas>
            </div>
        </>
    );
}
export default LeftRuler;
